import React, { useState, useEffect, useRef } from 'react';
import AMapLoader from '@amap/amap-jsapi-loader';
import { marineApi } from '@/api';
import './MarineMap.css';
import { Table, Modal, Button, Tooltip, Input } from 'antd';
import { message } from 'antd';
import { QuestionCircleOutlined } from '@ant-design/icons';

const MarineMap = () => {
  const [marineAreas, setMarineAreas] = useState([]);
  const mapRef = useRef(null);
  const markersRef = useRef([]);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [scoreData, setScoreData] = useState(null);
  const [loading, setLoading] = useState(false);
  const [policyState, setPolicyState] = useState({});

  // 找到数组的最大项的industry_type值
  const findMaxItem = (array) => {
    if (!array || array.length === 0) return null;
    let maxScore = Math.max(...array.map(item => item.score));
    for (let i = 0; i < array.length; i++) {
      if (array[i].score === maxScore) {
        return array[i].industry_type;
      }
    } 
  };

  // 根据industry_type值返回产业类型
  const typeMap = {
    'fishery': '渔业',
    'shipping': '航运业',
    'tourism': '旅游业',
    'energy': '能源',
    'aquaculture': '养殖业',
    'biotechnology': '生物技术'
  };

  // 定义表格列
  const columns = [
    {
      title: '产业类型',
      dataIndex: 'industry_type',
      key: 'industry_type',
      render: (text) => {
        return typeMap[text] || text;
      }
    },
    {
      title: '评分',
      dataIndex: 'score',
      key: 'score'
    },
    {
      title: '评估日期',
      dataIndex: 'evaluation_date',
      key: 'evaluation_date'
    },
    {
      title: '政策因素',
      key: 'policy',
      render: (text, record) => {
        const rowKey = `${record.industry_type}-${record.evaluation_date}`;
        const state = policyState[rowKey] || {};
        if (!state.type) {
          return (
            <>
              <Button color="primary" variant="solid" onClick={() => handlePolicyClick(rowKey, 'support')}>政策支持</Button>
              <Button color="cyan" variant="solid" style={{marginLeft: 8}} onClick={() => handlePolicyClick(rowKey, 'protect')}>环境政策保护</Button>
            </>
          );
        } else {
          return (
            <>
              <span style={{marginRight: 8,cursor: 'pointer'}} onClick={() => handlePolicyClick(rowKey, state.type === 'support' ? 'protect' : 'support')}>{state.type === 'support' ? '政策支持' : '环境政策保护'}</span>
              <Input
                style={{width: 200}}
                placeholder="请输入调整比值(范围0-0.2)"
                size="small"
                type="number"
                min={0}
                max={0.2}
                step={0.01}
                onPressEnter={e => handlePolicyInput(rowKey, e, record.score)}
              />
            </>
          );
        }
      }
    },
    {
      title: '最终产业得分',
      key: 'finalScore',
      render: (text, record) => {
        const rowKey = `${record.industry_type}-${record.evaluation_date}`;
        const state = policyState[rowKey] || {};
        return state.finalScore || '-';
      }
    }
  ];

  // 初始化地图
  useEffect(() => {
    window._AMapSecurityConfig = {
      securityJsCode: '36e9b8797cd9e7e0f2261d775e2e1530',
    };

    AMapLoader.load({
      key: '7784e8af655e42cb6422305d915f200b',
      version: '2.0',
      plugins: ['AMap.Scale', 'AMap.ToolBar', 'AMap.MarkerClusterer']
    })
    .then((AMap) => {
      mapRef.current = new AMap.Map('container', {
        viewMode: '3D',
        zoom: 9,
        center: [119.5, 38.5], //渤海为中心的经纬度
        pitch: 45,
        rotation: 0
      });

      // 添加工具条和比例尺
      mapRef.current.addControl(new AMap.Scale());
      mapRef.current.addControl(new AMap.ToolBar());
    })
    .catch(e => {
      console.error('地图加载失败：', e);
    });

    return () => {
      if (mapRef.current) {
        mapRef.current.destroy();
      }
    };
  }, []); // 只在组件挂载时执行一次

  // 获取海域数据
  useEffect(() => {
    marineApi.getAllAreas()
      .then(response => {
        console.log('获取到的海域数据:', response);
        // 注意这里不需要 response.data
        setMarineAreas(response);
      })
      .catch(error => {
        console.error('获取海域数据失败:', error);
        setMarineAreas([]);
      });
  }, []);

  // 更新标记点
  useEffect(() => {
    if (!mapRef.current || !marineAreas.length) {
      console.log('地图未初始化或没有海域数据');
      return;
    }

    console.log('开始更新地图标记，海域数据:', marineAreas);

    // 清除旧的标记点
    markersRef.current.forEach(marker => {
      marker.setMap(null);
    });
    markersRef.current = [];

    // 添加新的标记点
    marineAreas.forEach(area => {
      console.log('处理海域:', area);

      // 定义海域范围的多边形坐标
      const areaPath = getAreaPath(area);
      console.log('海域范围坐标:', areaPath);
      
      // 创建多边形
      const polygon = new window.AMap.Polygon({
        path: areaPath,
        strokeColor: "transparent",
        strokeWeight: 0,
        fillColor: 'transparent',
        fillOpacity: 0,
        cursor: 'pointer',
        bubble: true
      });

      polygon.setMap(mapRef.current);
      markersRef.current.push(polygon);

      // 添加区域名称标签
      const center = polygon.getBounds().getCenter();
      console.log('标签位置:', center);
      
      const text = new window.AMap.Text({
        text: area.area_name,
        position: center,
        style: {
          'background-color': 'transparent',
          'border-color': 'transparent',
          'text-align': 'center',
          'font-size': '20px',
          'font-weight': 'bold',
          'color': '#333',
          'cursor': 'pointer',
          'padding': '10px 20px'
        },
        clickable: true
      });

      text.setMap(mapRef.current);
      markersRef.current.push(text);

      // 给文字添加点击事件
      text.on('click', async () => {
        try {
          setLoading(true);
          const response = await marineApi.getAreaScores(area.id);
          console.log('点击海域:', response.area_name);
          console.log('获取到的评分数据:', response);
          setScoreData(response);
          setIsModalVisible(true);
        } catch (error) {
          console.error('获取评分数据失败:', error);
          message.error('获取评分数据失败');
        } finally {
          setLoading(false);
        }
      });
    });
  }, [marineAreas]);

  // 根据海域获取多边形路径
  const getAreaPath = (area) => {
    const center = [
      parseFloat(area.location?.lng || area.location_lng || 119.5),
      parseFloat(area.location?.lat || area.location_lat || 38.5)
    ];
    
    // 根据不同海域返回不同的多边形坐标
    switch(area.name || area.area_name) {
      case '渤海':
        return [
          [117.5, 37.5],
          [117.5, 41],
          [121, 41],
          [121, 37.5]
        ];
      case '黄海':
        return [
          [121, 31],
          [121, 36],
          [124, 36],
          [124, 31]
        ];
      case '东海':
        return [
          [121, 25],
          [121, 31],
          [125, 31],
          [125, 25]
        ];
      default:
        // 如果没有预定义的范围，创建一个以中心点为基础的矩形
        return [
          [center[0] - 1, center[1] - 1],
          [center[0] - 1, center[1] + 1],
          [center[0] + 1, center[1] + 1],
          [center[0] + 1, center[1] - 1]
        ];
    }
  };

  // 添加建议提示函数
  const getSuggestion = (score) => {
    if (score >= 80) {
      return "该海域生态数据正常，但仍须坚持可持续发展理念。";
    } else if (score >= 60) {
      return "当前海域需要减少产业开发投入，增加环保措施。";
    } else {
      return "环境保护刻不容缓，需要立马行动，建议暂缓产业开发。";
    }
  };

  const getScoreRange = (score) => {
    if (score >= 80) {
      return "high";
    } else if (score >= 60) {
      return "medium";
    } else {
      return "low";
    }
  };

  // 处理按钮点击
  const handlePolicyClick = (rowKey, type) => {
    setPolicyState(prev => ({
      ...prev,
      [rowKey]: { type, value: '', finalScore: undefined }
    }));
  };

  // 处理输入回车
  const handlePolicyInput = (rowKey, e, score) => {
    let val = parseFloat(e.target.value);
    if (isNaN(val) || val < 0 || val > 0.2) {
      message.warning('请输入0-0.2之间的数字');
      return;
    }
    let type = policyState[rowKey]?.type;
    let finalScore = type === 'support'
      ? score + score * val
      : score - score * val;
    // 如果最终得分大于100，则设置为100
    if (finalScore > 100) {
      finalScore = 100.00;
    }
    setPolicyState(prev => ({
      ...prev,
      [rowKey]: { ...prev[rowKey], value: val, finalScore: finalScore.toFixed(2) }
    }));
    setScoreData(prev => ({
      ...prev,
      scores: prev.scores.map(score => 
        score.industry_type === rowKey.split('-')[0] 
          ? { ...score, score: finalScore }
          : score
        )
      })
    );
  };

  return (
    <>
      <div className="inner-banner">
        <section className="w3l-breadcrumb">
          <div className="container">
            <ul className="breadcrumbs-custom-path">
              <li><a href="/">首页</a></li>
              <li className="active"><span className="fa fa-chevron-right mx-2" aria-hidden="true"></span> 海域地图</li>
            </ul>
          </div>
        </section>
      </div>
      <div className="marine-map-container">
        <div id="container" className="map-container"></div>
        <div className="map-legend">
          <h3>生态评分</h3>
          <div className="legend-item">
            <span className="legend-color high"></span>
            <span>优秀 (80-100分)</span>
          </div>
          <div className="legend-item">
            <span className="legend-color medium"></span>
            <span>良好 (60-79分)</span>
          </div>
          <div className="legend-item">
            <span className="legend-color low"></span>
            <span>待改进 (0-59分)</span>
          </div>
        </div>
      </div>

      {/* 添加弹窗 */}
      <Modal
        title={
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <span>{scoreData?.area_name ? `${scoreData.area_name}产业得分` : '产业得分'}</span>
            <div className="score-legend">
              <Tooltip title={getSuggestion(scoreData?.average_score)}>
                <Button 
                  type="text" 
                  icon={<QuestionCircleOutlined />}
                  style={{ color: '#1890ff' }}
                  className="suggestion-button"
                >
                  生态建议
                </Button>
              </Tooltip>
              <div className="legend-item button-score-legend">
                <span className={`legend-color ${getScoreRange(scoreData?.average_score)}`}></span>
              </div>
            </div>
          </div>
        }
        open={isModalVisible}
        onCancel={() => setIsModalVisible(false)}
        footer={null}
        width={800}
      >
        <h6>当前海域最适合发展的产业为：{typeMap[findMaxItem(scoreData?.scores)]}</h6>
        <Table
          columns={columns}
          dataSource={scoreData?.scores || []}
          loading={loading}
          rowKey={(record) => `${record.industry_type}-${record.evaluation_date}`}
          pagination={false}
        />
      </Modal>
    </>
  );
};

export default MarineMap; 